# analyze nationally representative survey questions from May 2015
# This script focuses not on region but on the cities in which IATs were conducted
# The survey had booster regions for Odesa, Kharkiv, Kyiv, but not Kherson.
# Kherson (urban) precincts are identified and coded based on values in the base. excel doc

library(haven)
library(survey)
library(tidyverse)
library(broom)
library(ggthemes)
library(stargazer)
# Load data and make survey object

rm(list = ls())

may15_svy <- read_rds(path = "./data_clean/rep_file_may15_svy.RDS")

may_svy_obj <- svydesign(ids = ~precinct,
                         strata = ~strata_code,
                         weights = ~rakedwt,
                         nest = TRUE,
                         data = may15_svy)
# generates Figure A.2

shelling_means <- svyby(~shelling_prob , by = ~ city, design = may_svy_obj, svymean, na.rm = TRUE, keep.var = TRUE)
gr_combat_means <- svyby(~gr_combat_prob , by = ~ city, design = may_svy_obj, svymean, na.rm = TRUE, keep.var = TRUE)
airstrike_means <- svyby(~airstrike_prob , by = ~ city, design = may_svy_obj, svymean, na.rm = TRUE, keep.var = TRUE)

calc_diffs <- function(data, event_val) {
  kharkiv <- svycontrast(data, list(diff=c(Kyiv=-1,Kharkiv=1)))  
  kherson <- svycontrast(data, list(diff=c(Kyiv=-1,Kherson=1)))
  odesa <- svycontrast(data, list(diff=c(Kyiv=-1,Odesa=1)))
  kharkiv_ci <- confint(kharkiv)
  kherson_ci <- confint(kherson)
  odesa_ci <- confint(odesa)
  
  as.data.frame(cbind(rbind(kharkiv, kherson, odesa),
                      rbind(kharkiv_ci, kherson_ci, odesa_ci))) %>%
    rename(diff = diff, low = `2.5 %`, high = `97.5 %`) %>%
    mutate(cities = rownames(.),
           event = event_val)
}

event_diffs <-
  calc_diffs(shelling_means, "shelling") %>%
  bind_rows(
    calc_diffs(gr_combat_means, "ground combat"),
    calc_diffs(airstrike_means, "airstrikes")
  ) %>%
  mutate(event = factor(event, levels = c("airstrikes",
                                          "shelling",
                                          "ground combat")))


ggplot(event_diffs, aes(x = event, y = diff, ymin = low, ymax = high,
                        color = cities, shape = cities)) +
  geom_pointrange(position = position_dodge(width = -0.5)) +
  geom_hline(yintercept = 0, color = "dark gray", linetype = "dashed") +
  coord_flip() +
  scale_shape_manual(values = c(19, 17, 15)) +
  labs(title = "Difference in means compared to Kyiv",
       x = NULL,
       y = NULL) +
  theme_tufte()

ggsave(filename = "plots/violence_expectation_diff.pdf",
       height = 4,
       width = 4) 

